package com.cumt.threeway.util;


import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cumt.threeway.R;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.view.dialog.MyDialog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

public class ThreeWayUtil {

	private final int CROP_IMAGE_SIZE = 300;
	private static final int MAX_WIDTH = 500;

	public static ThreeWayUtil twUtil;
	private ThreeWayUtil() {
		
	}
	
	public static synchronized ThreeWayUtil getInstance() {
		if(twUtil == null) {
			twUtil = new ThreeWayUtil();
		}
		return twUtil;
	}

	// 检测网络
	public NetworkInfo checkNetwork(Context context) {
		if (context == null) {
			return null;
		}
		NetworkInfo networkInfor = null;
		ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMan != null) {
			NetworkInfo[] info = conMan.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						networkInfor = info[i];
						break;
					}
				}
			}
		}
		return networkInfor;
	}

	//验证手机号码的格式
	public boolean isPhoneNum(String inputContent) {
		if(!TextUtils.isEmpty(inputContent)){
			String string = "1[2|3|4|5|6|7|8|9][0-9]{9}";
			Pattern pattern = Pattern.compile(string);
			if(!pattern.matcher(inputContent).matches()) {
				return true;
			}
		}
		return false;
	}

//	public boolean isPhoneNum(String inputContent) {
//		if(!TextUtils.isEmpty(inputContent)){
//			inputContent = inputContent.trim();
//			if (TextUtils.isDigitsOnly(inputContent) && inputContent.length() == 11) {
//				return true;
//			}
//		}
//		return false;
//	}

	// 提示框
	public Dialog showToast(Context context, String content) {
		View view = LayoutInflater.from(context).inflate(R.layout.dialog_toast_layout,null);
		TextView contentView = (TextView) view.findViewById(R.id.txt_toastcontent);
		contentView.setText(content);
		final MyDialog dialog = new MyDialog(context);
		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		if(context != null){
			dialog.show();
		}
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		}, 1000);
		return dialog;
	}

	public Dialog showToast(Context context, String content,long duration) {
		View view = LayoutInflater.from(context).inflate(R.layout.dialog_toast_layout,null);
		TextView contentView = (TextView) view.findViewById(R.id.txt_toastcontent);
		contentView.setText(content);
		final MyDialog dialog = new MyDialog(context);
		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		}, duration);
		return dialog;
	}

	public Dialog showToast(Context context, String title, String content,long duration) {
		View view = LayoutInflater.from(context).inflate(R.layout.dialog_toast_layout, null);
		TextView contentView = (TextView) view.findViewById(R.id.txt_toastcontent);
		TextView titleView = (TextView) view.findViewById(R.id.txt_toast_title);
		titleView.setText(title);
		contentView.setText(content);
		final MyDialog dialog = new MyDialog(context);
		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		}, duration);
		return dialog;
	}
	
	public String getIsFirstIn(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences("saveDetail", Context.MODE_PRIVATE);
		return sharedPreferences.getString("isFirstIn", "");
	}
	
	public void setFirstIn(Context context, String isFirstIn) {
		SharedPreferences sharedPreferences = context.getSharedPreferences("saveDetail", Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString("isFirstIn", isFirstIn);
		editor.commit();
	}

	public String getIsLoadData(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences("saveDetail", Context.MODE_PRIVATE);
		return sharedPreferences.getString("isLoadData", "");
	}

	public void setLoadData(Context context, String isFirstIn) {
		SharedPreferences sharedPreferences = context.getSharedPreferences("saveDetail", Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString("isLoadData", isFirstIn);
		editor.commit();
	}

	public void savePicture(String path, Bitmap bitmap) {
		savePicture(path, bitmap, 100);
	}

	public void savePicture(String path, Bitmap bitmap, int quality) {
		if (TextUtils.isEmpty(path) || (bitmap == null)) {
			return;
		}
		try {
			FileOutputStream fout = new FileOutputStream(path);
			BufferedOutputStream bos = new BufferedOutputStream(fout);
			//将bitmap保存为jpeg格式的文件
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean startPhotoZoom(Activity context,Uri uri) {
		if (uri == null) {
			return false;
		}
		boolean isCallSucceed = true;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", CROP_IMAGE_SIZE);
		intent.putExtra("outputY", CROP_IMAGE_SIZE);
		intent.putExtra("return-data", true);
		try {
			context.startActivityForResult(intent, ThreeWayConstant.REQUEST_CODE_FOR_CROP);
		} catch (ActivityNotFoundException e) {
			isCallSucceed = false;
		}
		return isCallSucceed;
	}

	public Bitmap createChangedImage(String path) {
		return createChangedImage(path, true);
	}

	public Bitmap createChangedImage(String path, boolean isAlpha) {
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		int minSize = Math.min(options.outWidth, options.outHeight);
		int maxSize = Math.max(options.outWidth, options.outHeight);
		if (minSize > (MAX_WIDTH * 2)) {
			options.inSampleSize = 2;
		} else if (minSize > MAX_WIDTH) {
			options.inSampleSize = 1;
		}
		if(maxSize > (MAX_WIDTH * 8)) {
			options.inSampleSize = 4;
		}
		if (!isAlpha) {
			options.inPreferredConfig = Bitmap.Config.RGB_565;
		}
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(path, options);
	}

	public static String getRealPathFromURI(final Context context, final Uri uri) {
		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(uri)) {
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[]{split[1]};

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} else if ("content".equalsIgnoreCase(uri.getScheme())) {
			if (isGooglePhotosUri(uri)) {
				return uri.getLastPathSegment();
			}

			return getDataColumn(context, uri, null, null);
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * [url=home.php?mod=space&uid=7300]@return[/url] The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = {column};

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	/**
	 * 下载用户头像  用于生成圆形头像
	 * @param url
	 * @param imageView
	 */
//	public void downloadUserIcon(final Context context,String url,final ImageView imageView){
//		if (!TextUtils.isEmpty(url) && imageView != null){
//			int start = url.lastIndexOf("/");
//			if(start!=-1){
//				final String urlPostFix = url.substring(start+1);
//				final String imgPath = ARUtil.getInstance().getAvatarAbsolutePath()+urlPostFix;
//				File file = new File(imgPath);
//				if((imgPath.endsWith(".jpg")||imgPath.endsWith(".png")||imgPath.endsWith(".jpeg"))&&file.exists()){
//					Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
//					imageView.setImageBitmap(bitmap);
//				}else{
//					//调用download方法开始下载
//					FinalHttp fh = new FinalHttp();
//					fh.download(url,imgPath, new AjaxCallBack<File>() {
//						@Override
//						public void onLoading(long count, long current) {
//							super.onLoading(count, current);
//						}
//						@Override
//						public void onSuccess(File t) {
//							super.onSuccess(t);
//							Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
//							imageView.setImageBitmap(bitmap);
//						}
//						@Override
//						public void onFailure(Throwable t, int errorNo,String strMsg) {
//							super.onFailure(t, errorNo, strMsg);
//							showCustomToast(context,context.getResources().getString(R.string.user_icon_download_failed), Toast.LENGTH_SHORT);
//						}
//					});
//				}
//			}
//		}
//	}

	public void saveLoginAccount(Context context, String string) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("userAccount", string);
		editor.commit();
	}

	public String getLoginAccount(Context context) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		return sharedPreferences.getString("userAccount", "");
	}

	public void saveUserName(Context context, String string) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("userName", string);
		editor.commit();
	}

	public String getUserName(Context context) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		return sharedPreferences.getString("userName", "");
	}

	public void saveThirdUserName(Context context, String string) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("thirdUserName", string);
		editor.commit();
	}

	public String getThirdUserName(Context context) {
		SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(ThreeWayConstant.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		return sharedPreferences.getString("thirdUserName", "");
	}

	/**
	 * 将时间戳转化成Date
	 * @param timestamp
	 * @return
	 */
	public String timestamp2Date(long timestamp) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return simpleDateFormat.format(new Date(timestamp));
	}

	}
